package com.yoo.ons.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.RequiresApi
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.yoo.module_base.utils.DateUtil.setStartSign
import com.yoo.module_base.utils.ScreenUtils
import com.yoo.module_base.utils.log
import com.yoo.module_base.utils.setSystemBottomNavBarColor
import com.yoo.module_base.utils.setSystemBottomNavBarNoColor
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.databinding.DialogProfileInfoBinding
import com.yoo.ons.dialog.viewmodel.ProInfoDialogViewModel
import com.yoo.ons.function.MainViewModel
import com.yoo.ons.function.like.viewmodel.WhoLikeMeViewModel
import com.yoo.ons.function.me.like.MyLikeListViewModel
import com.yoo.ons.function.me.viewmodel.MeViewModel
import com.yoo.ons.model.UserInfoModel
import com.yoo.ons.util.dpToPx
import com.yoo.ons.util.screenHeight

/**
 * 用户信息弹窗
 * */
class ProfileInfoDialogFragment : BottomSheetDialogFragment() {
    private var innerBinding: DialogProfileInfoBinding? = null
    private val binding get() = innerBinding!!
    private val openType by lazy { arguments?.getInt(PROFILE_INFO_OPEN_TYPE)!! }
    private val userCode by lazy { arguments?.getString(PROFILE_INFO_USER_CODE)!! }
    private lateinit var behavior: BottomSheetBehavior<FrameLayout>
    private val mainViewModel by lazy {
        ViewModelProvider(requireActivity())[MainViewModel::class.java]
    }
    private val meViewModel by lazy {
        ViewModelProvider(requireActivity())[MeViewModel::class.java]
    }
    private val wlmViewModel by lazy {
        ViewModelProvider(requireActivity())[WhoLikeMeViewModel::class.java]
    }
    private val myLikeViewModel by lazy {
        ViewModelProvider(requireActivity())[MyLikeListViewModel::class.java]
    }
    private val proInfoViewModel by lazy {
        ViewModelProvider(requireActivity())[ProInfoDialogViewModel::class.java]
    }
    private var dialogProfileBtn: ProfileInfoBottomMenuDialog? = null
    private var proInfoTopDialogFragment: ProInfoTopDialogFragment? = null
    private var clickType: Int = -1
    private var minHeight: Int = 0
    override fun getTheme(): Int {
        return com.yoo.module_res.R.style.Theme_Light_NoTitle_NoShadow_Dialog
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.window?.setWindowAnimations(com.yoo.module_base.R.style.BaseDialog_AnimationStyle)
        return dialog
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding = innerBinding
            ?: DialogProfileInfoBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        //底部按钮弹窗关闭
        dialogProfileBtn?.dismiss()
        //发送一个状态让首页卡片可以恢复滑动
        mainViewModel.slideCardState(true)
        if (clickType != -1) {
            //首页点击喜欢和不喜欢 然后再关闭弹窗的时候触发行为
            when (openType) {
                0 -> {
                    //home
                    mainViewModel.clickMenuType(clickType)
                }

                1 -> {
                    //wlm
                    wlmViewModel.clickLikeType(clickType)
                }

                2 -> {
                    //i like
                    myLikeViewModel.clickFcType(clickType)
                }
            }
        }
    }

    //获取model信息
    private fun getUserInfo() {
        meViewModel.getUserInfo(object : HttpRequestListener<UserInfoModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["userCode"] = userCode
            }

            override fun success(t: UserInfoModel?) {
            }
        })
    }

    //setUserInfo
    @SuppressLint("SetTextI18n")
    private fun setUserInfo(bean: UserInfoModel?) {
//        if (openType == 1) {
//            //屏蔽点击关闭
//            dialog?.setCanceledOnTouchOutside(false)
//        }
        bean?.let {
            binding.txtProfileInfoName.text = "${it.nickName},${it.age}"
            binding.txtProfileInfoAboutMe.text = it.aboutMe
            binding.txtProfileInfoLook.text = it.socialConnections

            binding.txtProfileInfoHeight.isVisible = it.inchHeight != null
            binding.txtProfileInfoHeight.text = it.inchHeight
            setStartSign(it.birthday, activity, binding.txtProfileInfoXz)
            binding.txtProfileInfoInterestsTag.setTags(it.interests)
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(Build.VERSION_CODES.S)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { setSystemBottomNavBarColor(it) }
        getUserInfo()
        meViewModel.userInfoLiveData.observe(viewLifecycleOwner) {
            setUserInfo(it)
        }
        proInfoViewModel.clickTopMiniLiveData.observe(viewLifecycleOwner) {
            if (it) {
                //点击了top需要把信息弹窗显示到屏幕的五分之一
                behavior.state = BottomSheetBehavior.STATE_COLLAPSED
                behavior.peekHeight = minHeight
            }
        }
        //一定要等view展示完之后再显示这个menu弹窗
        view.post {
            activity?.let {
                if (openType == 1 || openType == 2 || openType == 3) {
                    //只有在wlm im ilike页面的时候需要显示这个最上层的弹窗view去控制信息弹窗的高度
                    proInfoTopDialogFragment = ProInfoTopDialogFragment.newInstance()
                    proInfoTopDialogFragment?.show(it.supportFragmentManager)
                }

                dialogProfileBtn = ProfileInfoBottomMenuDialog.Builder(it)
                    .setCallback(object : ProfileInfoBottomMenuDialog.Callback {
                        override fun onBackClick(type: Int) {
                            clickType = type
                            dismissAllowingStateLoss()
                        }
                    }, openType).create()
                dialogProfileBtn?.show()
            }
        }

        dialog?.setOnShowListener { dialog ->
            val bottomSheet =
                (dialog as BottomSheetDialog).findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)
            if (bottomSheet != null) {
                behavior = BottomSheetBehavior.from(bottomSheet)
                //设置了最高高度 减去状态栏+返回按钮
                if (openType == 1 || openType == 2 || openType == 3) {
                    setupFullHeight(bottomSheet)
                }
                //如果是私信或者wlm下滑只显示到屏幕的20%高度
                minHeight = resources.displayMetrics.heightPixels / 5
                //默认打开显示屏幕一半
                behavior.peekHeight = resources.displayMetrics.heightPixels / 2
                behavior.state = BottomSheetBehavior.STATE_COLLAPSED
                behavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
                    override fun onStateChanged(bottomSheet: View, newState: Int) {
                        log("onStateChanged newState=$newState")
                        if (openType == 1 || openType == 2 || openType == 3) {
                            if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                                //bottomSheet.setPadding(0, ScreenUtils.getStatusBarHeight(activity)+ dpToPx(45), 0, 0)
                                //展开 隐藏顶部的view
                                proInfoViewModel.showProfileInfoTopView(false)
                            } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                                //bottomSheet.setPadding(0, 0, 0, 0)
                                //折叠 显示view
                                proInfoViewModel.showProfileInfoTopView(true)
                            }
                        }
                        //3展开 4折叠（一半或者最底部）
//                        if (newState == BottomSheetBehavior.STATE_DRAGGING) {
//                            if (behavior.peekHeight == resources.displayMetrics.heightPixels / 2) {
//                            }
//                        } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
//                            behavior.peekHeight = resources.displayMetrics.heightPixels / 2
//                        } else if (newState == BottomSheetBehavior.STATE_EXPANDED) {
//                        }
                    }

                    override fun onSlide(bottomSheet: View, slideOffset: Float) {
                        //当只有wlm和im这个页面去触发这个弹窗的时候才走这个逻辑
//                        if (openType == 1 || openType == 2 || openType == 3) {
//                            if (calculateBottomSheetHeight(bottomSheet, slideOffset) <= minHeight) {
//                                if (!isMinHeight) {
//                                    isMinHeight = true
//                                    behavior.state = BottomSheetBehavior.STATE_COLLAPSED
//                                    behavior.peekHeight = minHeight
//                                }
//                            }
//                        }
                    }
                })
            }
        }
        //1wlm 2ilike 3im
        if (openType == 1 || openType == 2 || openType == 3) {
            dialog?.setOnKeyListener(onBackListener)
        }
    }

    private fun calculateBottomSheetHeight(bottomSheet: View, slideOffset: Float): Int {
        val expandedHeight = bottomSheet.height
        val collapsedHeight = behavior.peekHeight
        val offsetHeight = ((expandedHeight - collapsedHeight) * slideOffset).toInt()
        return collapsedHeight + offsetHeight
    }

    private fun setupFullHeight(bottomSheet: FrameLayout) {
        val layoutParams = bottomSheet.layoutParams as CoordinatorLayout.LayoutParams
        layoutParams.height =
            screenHeight() - (ScreenUtils.getStatusBarHeight(activity) + dpToPx(45))
        bottomSheet.layoutParams = layoutParams
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //销毁底部按钮弹窗Dialog
        dialogProfileBtn?.dismiss()
        //top弹窗也需要去销毁
        proInfoTopDialogFragment?.dismissAllowingStateLoss()
        innerBinding = null
        activity?.let { setSystemBottomNavBarNoColor(it) }
        dismissAllowingStateLoss()
    }

    private val onBackListener = object : DialogInterface.OnKeyListener {
        override fun onKey(p0: DialogInterface?, p1: Int, p2: KeyEvent?): Boolean {
            if (p1 == KeyEvent.KEYCODE_BACK) {
                meViewModel.closeProfileDialog(true)
                return false
            }
            return false
        }
    }

    companion object {
        private const val PROFILE_INFO_USER_CODE = "PROFILE_INFO_USER_CODE"
        private const val PROFILE_INFO_OPEN_TYPE = "PROFILE_INFO_OPEN_TYPE"//0首页 1wlm 2ilike 3im
        fun newInstance(userCode: String, openType: Int): ProfileInfoDialogFragment {
            return ProfileInfoDialogFragment().apply {
                arguments = Bundle().apply {
                    putString(PROFILE_INFO_USER_CODE, userCode)
                    putInt(PROFILE_INFO_OPEN_TYPE, openType)
                }
            }
        }
    }
}